package com.sywb.chuangyebao.widget;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.czt.mp3recorder.MP3Player;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.utils.GlideUtils;

import org.bining.footstone.log.Logger;
import org.bining.footstone.utils.ToastUtils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

/**
 * 语音播放控件
 * Created by 55341 on 2018/3/23.
 */

public class AudioSeekBar extends FrameLayout {

    @BindView(R.id.iv_media)
    ImageView ivMedia;
    @BindView(R.id.iv_media_type)
    ImageView ivMediaType;
    @BindView(R.id.tv_current_time)
    TextView tvCurrentTime;
    @BindView(R.id.seekbar)
    SeekBar seekbar;
    @BindView(R.id.tv_audio_time)
    TextView tvAudioTime;
    @BindView(R.id.ll_media)
    LinearLayout llMedia;

    private Activity mActivity;
    private String audioUrl;

    public AudioSeekBar(@NonNull Context context) {
        super(context);
        initView(context);
    }

    public AudioSeekBar(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public AudioSeekBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public AudioSeekBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context);
    }

    private void initView(Context context) {
        mActivity = (Activity) context;

        inflate(mActivity, R.layout.layout_audio_seekbar, this);

        ivMedia = findViewById(R.id.iv_media);
        ivMediaType = findViewById(R.id.iv_media_type);
        tvCurrentTime = findViewById(R.id.tv_current_time);
        seekbar = findViewById(R.id.seekbar);
        tvAudioTime = findViewById(R.id.tv_audio_time);
        llMedia = findViewById(R.id.ll_media);

        ivMediaType.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (initMp3Player()) {
                    mp3Player.start();
                    startView();
                    return;
                }
                playOrPause();
            }
        });
    }

    private boolean isPlaying;


    private void startView() {
        ivMediaType.setImageResource(R.drawable.stop_video_l);
        isPlaying = true;
    }

    private void playOrPause() {
        if (isPlaying) {
            mp3Player.pause();
            ivMediaType.setImageResource(R.drawable.icon_media_audio);
            stopTimer();
        } else {
            mp3Player.restart();
            ivMediaType.setImageResource(R.drawable.stop_video_l);
            startTimer();
        }
        isPlaying = !isPlaying;
    }

    public void setAudioInfo(String imageUrl, String audioTime, final String audioUrl) {
        this.audioUrl = audioUrl;
        GlideUtils.getNormalIamgeToUrl(mActivity, imageUrl, ivMedia);
        String audioLength;
        final int audio;
        if (audioTime.contains(":")) {
            audioLength = audioTime;
            audio = Integer.valueOf(audioTime.substring(audioTime.indexOf(":") + 1));
        } else {
            audioLength = "0:" + (Integer.valueOf(audioTime) > 9 ? audioTime : "0" + audioTime);
            audio = Integer.valueOf(audioTime);
        }
        tvAudioTime.setText(audioLength);


        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (tvCurrentTime.getText().toString().equals(DateTimeUtils.getMediaTimeNumber(seekBar.getProgress() / 1000))) {
                    return;
                }
                tvCurrentTime.setText(DateTimeUtils.getMediaTimeNumber(seekBar.getProgress() / 1000));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Logger.e("onStopTrackingTouch:" + seekBar.getProgress());
                if (initMp3Player()) {
                    mp3Player.start();
                    startView();
                    tvCurrentTime.setText(DateTimeUtils.getMediaTimeNumber(seekBar.getProgress() * audio / 100));
                    return;
                }
                isPlaying = true;
                playOrPause();
            }
        });
    }


    public void destroy() {
        if (mp3Player != null) {
            mp3Player.destroy();
        }
    }

    private MP3Player mp3Player;


    private boolean initMp3Player() {
        if (mp3Player == null) {
            mp3Player = MP3Player.getInstance();
            mp3Player.prepare(audioUrl);
            mp3Player.setOnMP3PlayerListener(new MP3Player.OnMP3PlayerListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    Logger.e("MediaPlayer onCompletion");
                    isPlaying = false;
                    stopTimer();
                    seekbar.setProgress(0);
                    ivMediaType.setImageResource(R.drawable.icon_media_audio);
                    tvCurrentTime.setText("00:00");
                }

                @Override
                public void onSeekComplete(MediaPlayer mediaPlayer) {
                    Logger.e("MediaPlayer onSeekComplete");
                }

                @Override
                public void onError(MediaPlayer mediaPlayer) {
                    onCompletion(mediaPlayer);
                    ToastUtils.show(mActivity, "播放错误,请稍候再试");
                }

            });

            mp3Player.setOnMP3PlayerStartListener(new MP3Player.onMP3PlayerStartListener() {
                @Override
                public void onStart(MediaPlayer mediaPlayer) {
                    Logger.e("duration:" + mp3Player.getMediaPlayer().getDuration());
                    seekbar.setMax(mp3Player.getMediaPlayer().getDuration());
                    tvAudioTime.setText(DateTimeUtils.getMediaTimeNumber(seekbar.getMax() / 1000));
                    startTimer();
                }
            });
            return true;
        }
        return false;
    }

    private Timer mTimer;
    private boolean isChanging = false;//互斥变量，防止定时器与SeekBar拖动时进度冲突


    private void startTimer() {
        if (seekbar.getProgress() > 0) {
//            mp3Player.getMediaPlayer().seekTo(seekbar.getProgress() * mp3Player.getMediaPlayer().getDuration() / 100);
            mp3Player.getMediaPlayer().seekTo(seekbar.getProgress());
        }

        //----------定时器记录播放进度---------//
        isChanging = false;
        mTimer = new Timer();
        TimerTask mTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (isChanging) {
                    return;
                }

                try {
                    if (mp3Player.getMediaPlayer() == null) {
                        return;
                    }

                    seekbar.setProgress(mp3Player.getMediaPlayer().getCurrentPosition());
                    Logger.e("currentPosition:" + mp3Player.getMediaPlayer().getCurrentPosition() + "seekBar:" + seekbar.getProgress());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        mTimer.schedule(mTimerTask, 0, 100);
    }


    private void stopTimer() {
        if (mTimer != null) {
            isChanging = true;
            mTimer.cancel();
            Logger.e("stopTimer");
        }
    }


}
